#!/usr/bin/env python3
#-*- coding=utf-8 -*-

import requests
import threading
import os
import hashlib
import time
import signal

POST_URL = "http://%s/minik-rec/file_download.php"
GET_URL = "http://192.168.1.72/test.php"
DIR_FILE = "."
global flag 

def getFileMd5(filename):
	if(not os.path.isfile(path)):
		return None
	fp = open(filename, 'rb')
	myhash = hashlib.md5()
	myhash.update(fp.read())
	hash_code = myhash.hexdigest()
	fp.close()
	return hash_code

def postFile(path, url):
	if(not os.path.isfile(path)):
		return
	key,extension =  os.path.splitext(os.path.basename(path))
	if extension != ".mp3":
		return
	files = {'file': open(path, 'rb')}
	header = dict()
	header['cmd'] = 'notify'
	header['key'] = key
	header['time'] = '1466756410'
	header['md5'] = 'd79f14a9ae939d9b31725789307ecc76'
	header['signature'] = '8fc0670e669ce1809141972c45b942aa7f88b291'
	r = requests.post(url, files=files, headers=header)
	fp = open("test.log", "a")
	fp.write("\n[%d] " %time.time() + ' ' + r.url + r.text)
	fp.close()
	print(r.url + ' ' + r.text)

def main():
	current_files = os.listdir(DIR_FILE)
	signal.signal(signal.SIGINT, signalHandler)
	global flag
	flag = True
	while flag:
		for current_file in current_files:
			r = requests.get(GET_URL);
			postFile(current_file, POST_URL % r.text.strip(' \n\r\t'))

def signalHandler(signum, frame):
	global flag
	flag = False
	print("sigint occur\n")

if __name__ == '__main__':
	main()

